package com.htx.zqs.blesmartmask.ui.fragment;

import android.Manifest;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Location;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.htx.zqs.blesmartmask.R;
import com.htx.zqs.blesmartmask.listeners.OkListener;
import com.htx.zqs.blesmartmask.ui.activity.OrderInfoActivity;
import com.htx.zqs.blesmartmask.utils.BlEUtile;
import com.htx.zqs.blesmartmask.utils.CameraUtil;
import com.htx.zqs.blesmartmask.utils.LocationUtil;
import com.htx.zqs.blesmartmask.utils.OkhttpUtils;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;

/**
 * Created by zhao on 2018/5/11.
 */

public class UserFragment extends BaseFragment {
    private static final int REGISTER = 201;
    private static final int LOGIN = 202;
    private static final int IMAGE = 100;
    private static final int UG = 203;
    @InjectView(R.id.fg_tv)
    TextView fgTv;
    @InjectView(R.id.fg_user_bt_register)
    Button fgUserBt;
    @InjectView(R.id.fg_user_bt_login)
    Button fgUserBtLogin;
    @InjectView(R.id.et_name)
    EditText etName;
    @InjectView(R.id.et_password)
    EditText etPassword;
    private TextView tv;
    private boolean flag;
    private Timer timer;
    private MyNetworkReceiver receiver;
    private String mac;
    private String phoneInfo;
    private OkhttpUtils registerOkHttp;
    private static String registerUrl = "http://47.106.141.175/szhtcht/cLanguage.link";
    private static String ugUrl = "http://47.106.141.175/szhtcht/ug.link";
    private String name;
    private String password;
    private Dialog mCameraDialog;
    private CameraUtil cameraUtil;
    private OkhttpUtils loginOkhttp;
    private OkhttpUtils ugOkhttp;
    private Location bestLocation;
    //LuckSiege -- 三方调用系统相册相机

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_test, container, false);
        tv = view.findViewById(R.id.fg_tv);
        tv.setText("北京市");

        initView();
        //   initDialog();
        ButterKnife.inject(this, view);
        return view;
    }

    private void initDialog() {
        cameraUtil = new CameraUtil();
        mCameraDialog = cameraUtil.getCameraDialog(getActivity(), btnlistener,R.layout.layout_camera_control,0);

    }


    private View.OnClickListener btnlistener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.btn_open_camera: // 打开照相机
                    cameraUtil.useCamera(getActivity(), 0);
                    break;
                // 打开相册
                case R.id.btn_choose_img:
                    cameraUtil.usePicture(getActivity());
                    break;
                // 取消
                case R.id.btn_start_Course:
                    if (mCameraDialog != null) {
                        mCameraDialog.dismiss();
                    }
                    break;
            }
        }
    };

    private void initView() {

        mac = BlEUtile.getMac(getContext());
        phoneInfo = LocationUtil.getPhoneInfo(getContext());
        Log.e("location", "onCreateView: " + phoneInfo);
        receiver = new MyNetworkReceiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
        getActivity().registerReceiver(receiver, intentFilter);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.reset(this);
    }

    @OnClick({R.id.fg_user_bt_register, R.id.fg_user_bt_login})
    public void onViewClicked(View view) {
        name = etName.getText().toString().trim();
        password = etPassword.getText().toString().trim();
        switch (view.getId()) {
            case R.id.fg_user_bt_register:
                //  register();
                // initDialog();
                ug();
               // showTv();
                break;
            case R.id.fg_user_bt_login:
                startActivity(new Intent(getContext(), OrderInfoActivity.class));
                //login();
                break;
        }
    }

    private void ug() {
        ugOkhttp = new OkhttpUtils(getActivity(), UG, mListener);
        HashMap hashMap = new HashMap();
        hashMap.put("sex", "男");
        hashMap.put("age", "25");
        hashMap.put("userge", "啥玩意");
        hashMap.put("uuid", "谁知道是啥");
        hashMap.put("phone", "12345676235");
        ugOkhttp.postForm(UG, ugUrl, hashMap);
    }


    private OkListener mListener = new OkListener() {
        @Override
        public void onSuccess(int requestCode, String string) {
            if (requestCode == REGISTER) {
                Log.e("ok", "onSuccess: " + string);
            } else if (requestCode == LOGIN) {
                Log.e("ok", "onSuccess: " + string);
            } else if (requestCode == UG) {
                Log.e("ok", "onSuccess: " + string);
            }
        }

        @Override
        public void onError(int requestCode, IOException e) {
            Log.e("ok", "onError: " + e);
        }
    };

    private void login() {
        loginOkhttp = new OkhttpUtils(getActivity(), LOGIN, mListener);
        HashMap hashMap = new HashMap();
        hashMap.put("language", "zh_CN");
        loginOkhttp.postForm(LOGIN, registerUrl, hashMap);
    }

    private void register() {
        registerOkHttp = new OkhttpUtils(getActivity(), REGISTER, mListener);
        HashMap hashMap = new HashMap();
        hashMap.put(name, password);
        registerOkHttp.postForm(REGISTER, registerUrl, hashMap);
    }


    public class MyNetworkReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            //**判断当前的网络连接状态是否可用*/
            ConnectivityManager connectivityManager =
                    (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo info = connectivityManager.getActiveNetworkInfo();
            if (info != null && info.isAvailable()) {
                //当前网络状态可用
                Log.e("gps", "run: 进来没" + 555);
                showTv();
                Log.e("gps", "run: 进来没" + 666);
                int netType = info.getType();
                if (netType == ConnectivityManager.TYPE_WIFI) {
                    Log.e("NETSTATUE", "当前网络状态为-wifi");
                } else if (netType == ConnectivityManager.TYPE_MOBILE) {
                    Log.e("NETSTATUE", "当前网络状态为-mobile");
                }
            } else {
                //当前网络不可用
                Log.e("NETSTATUE", "无网络连接");
            }
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (timer != null){
            timer.cancel();
        }
        getActivity().unregisterReceiver(receiver);
    }

    private void showTv() {
        Log.e("gps", "run: 进来没" + 111);
        timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                /**
                 * 要循环执行的代码
                 */
                if (flag) {
                    Log.e("gps", "run: 进来没" + "aaa");
                    final String city;
                    bestLocation = LocationUtil.getBestLocation(getContext());
                    List<Address> locationInfos = LocationUtil.getLocationInfo(bestLocation, getContext());
                    if (locationInfos == null ||locationInfos.size() == 0) {
                        city = "";
                    } else {
                        city = locationInfos.get(0).getAdminArea() + locationInfos.get(0).getLocality();
                    }
                    Log.e("gps", "run: 进来没" + bestLocation);
                    Log.e("gps", "run: 进来没" + locationInfos);
                    new Handler(Looper.getMainLooper()).post(new Runnable() {
                        @Override
                        public void run() {
                            Log.e("gps", "run: 进来没" + flag);
                            // 主线程开始搞事儿
                            tv.setText(city + "经度:" + bestLocation.getLatitude() + "纬度" + bestLocation.getLongitude());
                        }
                    });

//                            for (String city : bestLocation.keySet()
//                                    ) {
//                                ArrayList<String> strings = bestLocation.get(city);
//                                Log.e("gps", "run: " + city + "经度：" + strings.get(0) + "纬度" + strings.get(1)
//                                        + "Mac:" + mac + "phoneInfo" + phoneInfo);
//                                Log.e("gps", "run: 进来没"+333 );
//                                tv.setText(city + "经度：" + strings.get(0) + "纬度" + strings.get(1) + "Mac:" + mac + "\n" + "phoneInfo" + phoneInfo);
//                            }
                }

// 定位  请求  间隔 时间  period
            }
        }, 1, 15 * 60 * 1000);

// 第一个参数：TimerTask类的对象，实现TimerTask的run()方法，即要周期执行的一个任务；
// 第二个参数：从定时器初始化成功，开始启动的延迟时间；第三个参数：定时器的间隔时间（执行的周期，long类型）。
    }


    @Override
    public void onResume() {
        super.onResume();
        initPermission();//针对6.0以上版本做权限适配
    }

    private void initPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            //检查权限
            if (ContextCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED
                    || ContextCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                //请求权限
                Log.e("permission", "onRequestPermissionsResult: 有权限了没");
                requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION}, 12);
            } else {
                flag = true;
            }
        } else {
            flag = true;
        }
    }

    /**
     * 权限的结果回调函数
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 12) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults[1] == PackageManager.PERMISSION_GRANTED) {
                Log.e("permission", "onRequestPermissionsResult: 有权限了没" + grantResults);
                flag = true;
            } else {
                Log.e("permission", "onRequestPermissionsResult: 有权限了没" + permissions);
                flag = false;
            }

        }
        if (requestCode == IMAGE) {

        }
    }
}
